package hsl.study.controller;


import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @Author: hsl
 * @CreateDate: 2025/8/1 9:35
 * @Version: 1.0
 */

@RestController
@RequestMapping("/blt2i")
public class Text2ImageController {
    // 导入image的专属model
    private static final String BAILIAN_IMAGE_MODEL = "wanx2.1-t2i-turbo";

    /**
     * @param msg
     * @return http://localhost:7008/blt2i/img1?msg=%E4%B8%80%E5%8F%AA%E7%8C%AB%E5%9C%A8%E7%AA%97%E6%88%B7%E5%89%8D%E7%9E%8C%E7%9D%A1
     * @throws NoApiKeyException
     */
    @GetMapping("/img1")
    public String img(String msg) throws NoApiKeyException {
        //图片生成器
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        // 图片参数设置
        ImageSynthesisParam param = ImageSynthesisParam.builder()
                .apiKey(System.getenv("LANGCHAIN_TONGYI"))
                .model(BAILIAN_IMAGE_MODEL)
                .prompt(msg)
                .n(1)
                .size("1024*1024")
                .build();
        // 生成图片
        ImageSynthesisResult imageSynthesisResult = imageSynthesis.call(param);

        //结果返回
        String result = imageSynthesisResult.getOutput()
                .getResults()
                .get(0)
                .get("url");
        System.out.println("result = " + result);
        return result;
    }

    /**
     * @return 看控制台的输出的url
     */
    @GetMapping("/img2")
    public String img2(@RequestParam String prompt) {
//        String prompt = "一间有着精致的花，漂亮的木质门，摆放着花朵";

        // 图片参数设置
        ImageSynthesisParam param = ImageSynthesisParam.builder()
                .apiKey(System.getenv("LANGCHAIN_TONGYI"))
                .model(BAILIAN_IMAGE_MODEL)
                .prompt(prompt)
                .n(1)
                .size("1024*1024")
                .build();

        //图片生成器
        ImageSynthesis imageSynthesis = new ImageSynthesis();

        // 生成图片
        ImageSynthesisResult imageSynthesisResult = null;

        try {
            System.out.println("---sync call, please wait a moment----");
            imageSynthesisResult = imageSynthesis.call(param);
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        }
        System.out.println(JsonUtils.toJson(imageSynthesisResult));
        return JsonUtils.toJson(imageSynthesisResult);
    }

}
